<template>
  <a-form :form="form" @submit="handleSubmit">
    <a-form-item label="项目名称" v-bind="formItemLayout">
      <a-input
        v-decorator="[
          'project_name',
          {
            initialValue: initInfo.project_name,
            rules: [
              { required: true, message: '必填项！' },
              {
                validator: $validate.validateLength,
                max: 20,
                min: 1
              }
            ]
          }
        ]"
      />
    </a-form-item>
    <a-form-item
      label="项目图"
      v-bind="formItemLayout"
      help="建议图片宽高为：200px*286px"
    >
      <div class="clearfix">
        <a-upload
          :disabled="optType === 3"
          v-decorator="[
            'upload',
            {
              initialValue: initInfo.upload,
              valuePropName: 'fileList',
              getValueFromEvent: normFile,
              rules: [{ required: true, message: '请上传项目图' }]
            }
          ]"
          accept="image/*"
          listType="picture-card"
          name="file"
          :multiple="false"
          :showUploadList="false"
          :action="$api.upload"
          :data="postData"
          :beforeUpload="beforeUpload"
        >
          <img
            v-if="imageUrl"
            :src="$api.picPre + imageUrl"
            alt="avatar"
            style="width: 64px"
          />
          <div v-else>
            <a-icon :type="loading ? 'loading' : 'plus'" />
            <div class="ant-upload-text">上传封面图</div>
          </div>
        </a-upload>
      </div>
    </a-form-item>
    <a-form-item label="特性一" v-bind="formItemLayout">
      <a-input
        v-decorator="[
          'character1',
          {
            initialValue: initInfo.character1,
            rules: [
              { required: true, message: '必填项！' },
              {
                validator: $validate.validateLength,
                max: 20,
                min: 1
              }
            ]
          }
        ]"
      />
    </a-form-item>
    <a-form-item label="特性一介绍" v-bind="formItemLayout">
      <a-input
        v-decorator="[
          'character1_info',
          {
            initialValue: initInfo.character1_info,
            rules: [
              { required: true, message: '必填项！' },
              {
                validator: $validate.validateLength,
                max: 20,
                min: 1
              }
            ]
          }
        ]"
      />
    </a-form-item>
    <a-form-item label="特性二" v-bind="formItemLayout">
      <a-input
        v-decorator="[
          'character2',
          {
            initialValue: initInfo.character2,
            rules: [
              { required: true, message: '必填项！' },
              {
                validator: $validate.validateLength,
                max: 20,
                min: 1
              }
            ]
          }
        ]"
      />
    </a-form-item>
    <a-form-item label="特性二介绍" v-bind="formItemLayout">
      <a-input
        v-decorator="[
          'character2_info',
          {
            initialValue: initInfo.character2_info,
            rules: [
              { required: true, message: '必填项！' },
              {
                validator: $validate.validateLength,
                max: 20,
                min: 1
              }
            ]
          }
        ]"
      />
    </a-form-item>
    <a-form-item label="特性三" v-bind="formItemLayout">
      <a-input
        v-decorator="[
          'character3',
          {
            initialValue: initInfo.character3,
            rules: [
              { required: true, message: '必填项！' },
              {
                validator: $validate.validateLength,
                max: 20,
                min: 1
              }
            ]
          }
        ]"
      />
    </a-form-item>
    <a-form-item label="特性三介绍" v-bind="formItemLayout">
      <a-input
        v-decorator="[
          'character3_info',
          {
            initialValue: initInfo.character3_info,
            rules: [
              { required: true, message: '必填项！' },
              {
                validator: $validate.validateLength,
                max: 20,
                min: 1
              }
            ]
          }
        ]"
      />
    </a-form-item>
    <a-form-item label="特性四" v-bind="formItemLayout">
      <a-input
        v-decorator="[
          'character4',
          {
            initialValue: initInfo.character4,
            rules: [
              { required: true, message: '必填项！' },
              {
                validator: $validate.validateLength,
                max: 20,
                min: 1
              }
            ]
          }
        ]"
      />
    </a-form-item>
    <a-form-item label="特性四介绍" v-bind="formItemLayout">
      <a-input
        v-decorator="[
          'character4_info',
          {
            initialValue: initInfo.character4_info,
            rules: [
              { required: true, message: '必填项！' },
              {
                validator: $validate.validateLength,
                max: 20,
                min: 1
              }
            ]
          }
        ]"
      />
    </a-form-item>
    <a-row>
      <a-col :span="24" :style="{ textAlign: 'center' }">
        <a-button type="primary" html-type="submit">
          提交
        </a-button>
        <a-button :style="{ marginLeft: '8px' }" @click="handleReset">
          重置
        </a-button>
      </a-col>
    </a-row>
  </a-form>
</template>

<script>
import { getToken } from "@/tool/qiniu";
import moment from "moment";
export default {
  name: "add",
  components: {},
  data() {
    return {
      formLayout: "horizontal",
      form: this.$form.createForm(this),
      previewVisible: false,
      fileList: [],
      previewImage: "",
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 }
        }
      },
      initInfo: {
        upload: []
      },
      postData: {
        token: ""
      },
      bgPostData: {
        token: ""
      },
      loading: false,
      imageUrl: "",
      optType: 1
    };
  },
  methods: {
    moment,
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          let obj = JSON.parse(JSON.stringify(values));
          if (values.upload) {
            obj.pic = values.upload[0].response.key;
            delete obj.upload;
          }
          let api = null;
          if (this.optType === 1) {
            api = this.$api.addProjectInfo;
            obj.type = 1;
          } else if (this.optType === 2) {
            api = this.$api.editProjectInfo;
            obj.id = this.$route.params.id;
            obj.type = 2;
          }
          this.$ajax
            .post(api, obj)
            .then(() => {
              this.$notification.success({
                message: "操作成功"
              });
              this.$router.push({ name: "projectList" });
            })
            .catch(err => {
              this.$notification.error({
                message: err
              });
            });
        }
      });
    },
    handleCancel() {
      this.form.resetFields();
      this.$emit("handleCancel");
    },
    handleReset() {
      this.form.resetFields();
    },
    beforeUpload(file) {
      let timestamp2 = new Date().getTime();
      let typeArr = file.name.split(".");
      let type = typeArr[typeArr.length - 1];
      let savekey = "/cxxy/project/" + timestamp2 + "." + type;
      this.postData.token = getToken(savekey);
      let _this = this;
      let imgWidth = "";
      let imgHight = "";
      const isSize = new Promise(function(resolve, reject) {
        let width = 200;
        let height = 286;
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          imgWidth = img.width;
          imgHight = img.height;
          let valid = img.width == width && img.height == height;
          valid ? resolve() : reject();
        };
        img.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          _this.$notification.error({
            message:
              "图片大小不符合标准,宽高为200px*286px。当前上传图片的宽高分别为：" +
              imgWidth +
              "px和" +
              imgHight +
              "px"
          });
          return Promise.reject();
        }
      );
      return isSize;
    },
    normFile(e) {
      if (e.file.status === "uploading") {
        this.loading = true;
        return e && e.fileList;
      } else if (e.file.status === "done") {
        this.imageUrl = e.file.response.key;
        this.loading = false;
        if (e.fileList.length > 1) {
          e.fileList.splice(0, 1);
        }
      }
      return e && e.fileList;
    },
    getInfo() {
      this.$ajax
        .get(this.$api.detailProjectInfo, {
          id: this.$route.params.id
        })
        .then(res => {
          this.initInfo = res;
          this.initInfo.upload = [
            {
              uid: "1",
              status: "done",
              url: this.$api.picPre + res.pic,
              name: res.title,
              response: {
                key: res.pic
              }
            }
          ];
          this.imageUrl = res.pic;
        })
        .catch(err => {
          this.$notification.error({
            message: err
          });
        });
    }
  },
  created() {
    if (this.$route.name === "editProject") {
      this.optType = 2;
      this.getInfo();
    } else {
      this.optType = 1;
    }
  }
};
</script>

<style scoped></style>
